package avicit.bdp.lineage.druid.process.tablesource;

import avicit.bdp.lineage.druid.anotation.SQLObjectType;
import avicit.bdp.lineage.druid.contants.ParserConstant;
import avicit.bdp.lineage.druid.model.TableNode;
import avicit.bdp.lineage.druid.model.TreeNode;
import avicit.bdp.lineage.druid.process.ProcessorRegister;
import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.statement.SQLJoinTableSource;
import com.alibaba.druid.sql.ast.statement.SQLLateralViewTableSource;
import com.alibaba.druid.sql.ast.statement.SQLTableSource;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * <p>
 * SQLLateralViewTableSource
 * </p>
 * <p>
 * select
 * user_id,
 * order_stats_struct.sku_id sku_id,
 * order_stats_struct.order_count order_count
 *  from dws_user_action_daycount lateral view explode(order_detail_stats) tmp as order_stats_struct
 * </p>
 */
@SQLObjectType(clazz = SQLLateralViewTableSource.class)
public class SQLLateralViewTableSourceProcessor implements TableSourceProcessor {

    @Override
    public void process(String dbType, AtomicInteger sequence, TreeNode<TableNode> parent,
                        SQLTableSource sqlTableSource) {
        // 建立中介节点 start
        TableNode proxyTable = TableNode.builder()
                .isVirtualTemp(true)
                .expression(SQLUtils.toSQLString(sqlTableSource))
                .name(ParserConstant.TEMP_TABLE_PREFIX + sequence.incrementAndGet())
             //   .alias(sqlTableSource.getAlias())
                .build();

        TreeNode<TableNode> proxyNode = TreeNode.of(proxyTable);
        parent.addChild(proxyNode);

        SQLLateralViewTableSource sqlJoinTableSource = (SQLLateralViewTableSource) sqlTableSource;
        ProcessorRegister.getTableSourceProcessor(sqlJoinTableSource.getTableSource().getClass())
                .process(dbType, sequence, proxyNode, sqlJoinTableSource.getTableSource());


    }

}
